'use strict';

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

var app = require('express')();
var cors = require('cors');
var fs = require('fs');
let rimraf = require('rimraf');
require('babel-polyfill');

let { gPDF } = require('./clip_web_chrome_headless_c');

app.use(cors());
app.use(function (req, res, next) {
  // console.log('%s %s', req.method, req.url);
  global.rightNow = new Date().getTime();
  var requestURL = req.url;
  console.log(requestURL);
  let match = requestURL.match(/([\d]*)\?template=(.*)*/);
  var hospitalId = decodeURI(match[1]);
  var templateId = decodeURI(match[2]);
  console.log("接收到的医院名称是", hospitalId);
  if (hospitalId && hospitalId.length !== 0 && hospitalId !== 'favicon.ico') {

    _asyncToGenerator(function* () {
      console.log("PDF切图进行中...");
      var pdfFile = yield gPDF(hospitalId, templateId);
      console.log('pdf地址', pdfFile);

      res.download(pdfFile, `${hospitalId}的报告.pdf`, function (err) {
        if (err) {
          // 处理错误，请牢记可能只有部分内容被传输，所以
          // 检查一下res.headerSent
          console.log("传递发生错误", err);
        } else {
          console.log('传递成功！！');
          //将存放pdf的临时文件夹删除掉

          fs.unlink(pdfFile, () => {
            console.log('文件' + pdfFile + '已经被删除了');
          });
        }
      });
    })();
  } else {
    res.send("请在链接的末尾加入医院名称, 形如http://10.0.1.135:3000/四川省人民医院");
  }
});

app.listen(3001, '0.0.0.0', () => {
  console.log('截图服务器运行中...');
});
